﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Data.OleDb;

namespace BawangMemo.BackendModels
{
    public class DataAccess
    {
        #region Database

        internal static void ExecuteNonQuery(OleDbConnection connection, string command)
        {
            OleDbCommand cmd = new OleDbCommand(command, connection);
            cmd.ExecuteNonQuery();
        }

        internal static OleDbDataReader ExecuteReader(OleDbConnection connection, string command)
        {
            OleDbCommand cmd = new OleDbCommand(command, connection);
            return cmd.ExecuteReader();
        }

        #endregion

        #region Serialization

        /// <summary>
        /// 将一个object对象序列化，返回一个byte[]
        /// </summary>
        /// <param name="obj">能序列化的对象</param>
        /// <param name="count">对象的大小</param>
        /// <returns>序列</returns>
        public static byte[] ObjectToBytes(object obj, int count)
        {
            using (MemoryStream ms = (count > 0 ? new MemoryStream(count) : new MemoryStream()))
            {
                IFormatter formatter = new BinaryFormatter();
                formatter.Serialize(ms, obj);
                return ms.GetBuffer();
            }
        }

        /// <summary>
        /// 将一个序列化后的byte[]数组还原
        /// </summary>
        /// <param name="bytes">序列</param>
        /// <returns>还原的对象</returns>
        public static object BytesToObject(byte[] bytes)
        {
            using (MemoryStream ms = new MemoryStream(bytes))
            {
                IFormatter formatter = new BinaryFormatter();
                return formatter.Deserialize(ms);
            }
        }
        #endregion

        /// <summary>
        /// Serialize an object to a file.
        /// </summary>
        /// <param name="object">the object</param>
        /// <param name="path">file path</param>
        internal static void ObjectToFile(object obj, string path)
        {
            using (FileStream fs = new FileStream(path, FileMode.Create))
            {
                BinaryFormatter bf = new BinaryFormatter();
                bf.Serialize(fs, obj);
                fs.Flush();
                fs.Close();
            }
        }

        /// <summary>
        /// Deserialize an object from a file.
        /// </summary>
        /// <param name="path">file path</param>
        /// <returns>the object</returns>
        internal static object FileToObject(string path)
        {
            using (FileStream fs = new FileStream(path, FileMode.Open))
            {
                BinaryFormatter bf = new BinaryFormatter();
                return bf.Deserialize(fs);
            }
        }
    }
}
